package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.ExcelUtil;
import cn.stylefeng.guns.sys.core.util.PageUtil;
import cn.stylefeng.guns.sys.modular.system.db4.mapper.BizShopMapper;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBrand;
import cn.stylefeng.guns.sys.modular.system.entity.BtyMdYydz;
import cn.stylefeng.guns.sys.modular.system.entity.BtyZxMdgz;
import cn.stylefeng.guns.sys.modular.system.entity.ExcelExp;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyBrandMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMdYydzDetailMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyMdYydzMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyMdYydzParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyMdYydzResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyMdYydzService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.HttpContext;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 门店营业额报备表 服务实现类
 * </p>
 *
 * @author 
 * @since 2021-12-03
 */
@Service
public class BtyMdYydzServiceImpl extends ServiceImpl<BtyMdYydzMapper, BtyMdYydz> implements BtyMdYydzService {

    @Resource
    private BtyBrandMapper brandMapper;
    @Resource
    private BizShopMapper shopMapper;
    @Resource
    private BtyMdYydzDetailMapper yydzDetailMapper;

    @Override
    public void add(BtyMdYydzParam param){
        BtyMdYydz entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyMdYydzParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyMdYydzParam param){
        BtyMdYydz oldEntity = getOldEntity(param);
        BtyMdYydz newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyMdYydzResult findBySpec(BtyMdYydzParam param){
        return null;
    }

    @Override
    public List<BtyMdYydzResult> findListBySpec(BtyMdYydzParam param){
        return null;
    }

    @Override
//    public LayuiPageInfo findPageBySpec(BtyMdYydzParam param){
//        //当前登陆者姓名
//        String name = LoginContextHolder.getContext().getUser().getName();
//        //当前登陆者角色
//        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
//
//        Page pageContext = getPageContext();
////        IPage page = this.baseMapper.customPageList(pageContext, param);
//        IPage page = null;
//
//        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
//            page = this.baseMapper.customPageList(pageContext, param, null);
//        }else if (roleNames.contains("应收会计")){
//            //获取应收会计所对应店名编号
//            List<String> bhList = this.baseMapper.bhList(name);
//            page = this.baseMapper.customPageList(pageContext, param, bhList);
//        }
//
//        List<BtyMdYydzResult> dataList = page.getRecords();
//        if (ToolUtil.isNotEmpty(dataList)){
//            //获取对应问题状态
//            List<Map> list = yydzDetailMapper.getSta(dataList);
//            Map<Integer, Map> hashMap = new HashMap<>();
//            if (ToolUtil.isNotEmpty(list)){
//                //取出数据
//                for (Map map : list) {
//                    hashMap.put(Integer.valueOf(map.get("yydz_id").toString()),map);
//                }
//            }
//
//            for (BtyMdYydzResult result : dataList) {
//                Map map = hashMap.get(result.getId());
//                if (ToolUtil.isNotEmpty(map)){
//                    result.setProType(map.get("sta").toString());//问题状态
//                    result.setBbCon(Integer.valueOf(map.get("bbCon").toString()));//店长报备数
//                    result.setCwCon(Integer.valueOf(map.get("cwCon").toString()));//财务审核数
//                }else {
//                    result.setProType("3");//问题状态;1->需核对,2->已解决,3->无
//                    result.setBbCon(0);//店长报备数
//                    result.setCwCon(0);//财务审核数
//                }
//            }
//            //排序
//            Collections.sort(dataList, new Comparator<BtyMdYydzResult>(){
//                @Override
//                public int compare(BtyMdYydzResult result1, BtyMdYydzResult result2) {
//                    return result1.getProType().compareTo(result2.getProType());
//                }
//            });
//        }
//
//        return LayuiPageFactory.createPageInfo(page);
//    }


    public LayuiPageInfo findPageBySpec(BtyMdYydzParam param, String date){
        HttpServletRequest request = HttpContext.getRequest();
        int limit = 20;
        int page = 1;
        //每页多少条数据
        String limitString = request.getParameter("limit");
        if (ToolUtil.isNotEmpty(limitString)) {
            limit = Integer.parseInt(limitString);
        }
        //第几页
        String pageString = request.getParameter("page");
        if (ToolUtil.isNotEmpty(pageString)) {
            page = Integer.parseInt(pageString);
        }

        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        Page pageContext = getPageContext();
        List<BtyMdYydzResult> resultList = new ArrayList<>();//店名列表

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            resultList = this.baseMapper.customPageList(param, null);
        }else if (roleNames.contains("应收会计")){
            //获取应收会计所对应店名编号
            List<String> bhList = this.baseMapper.bhList(name);
            resultList = this.baseMapper.customPageList(param, bhList);
        }

        if (ToolUtil.isNotEmpty(resultList)){
            //获取对应问题状态
            List<Map> list = yydzDetailMapper.getSta(resultList, date);
            Map<Integer, Map> hashMap = new HashMap<>();
            if (ToolUtil.isNotEmpty(list)){
                //取出数据
                for (Map map : list) {
                    hashMap.put(Integer.valueOf(map.get("yydz_id").toString()),map);
                }
            }

            Integer dzTol = 0;
            Integer cwTol = 0;
            for (BtyMdYydzResult result : resultList) {
                Map map = hashMap.get(result.getId());
                if (ToolUtil.isNotEmpty(map)){
                    result.setProType(map.get("sta").toString());//问题状态
                    result.setBbCon(Integer.valueOf(map.get("bbCon").toString()));//店长报备数
                    result.setCwCon(Integer.valueOf(map.get("cwCon").toString()));//财务审核数
                }else {
                    result.setProType("3");//问题状态;1->需核对,2->已解决,3->无
                    result.setBbCon(0);//店长报备数
                    result.setCwCon(0);//财务审核数
                }
                dzTol = dzTol + result.getBbCon();//店长报备总数
                cwTol = cwTol + result.getCwCon();//财务审核情况
            }

            //根据问题状态筛选数据
            if (ToolUtil.isNotEmpty(param.getProType())){
                resultList = resultList.stream().filter(u -> param.getProType().equals(u.getProType())).collect(Collectors.toList());
            }

            if (ToolUtil.isNotEmpty(resultList)){
                for (BtyMdYydzResult result : resultList) {
                    result.setDzTol(dzTol);//店长报备总数
                    result.setCwTol(cwTol);//财务审核情况
                    result.setMdTol(resultList.size());//需核对门店数
                }
            }

            //排序
            Collections.sort(resultList, new Comparator<BtyMdYydzResult>(){
                @Override
                public int compare(BtyMdYydzResult result1, BtyMdYydzResult result2) {
                    return result1.getProType().compareTo(result2.getProType());
                }
            });
        }

        //分页
        IPage page1 = new Page();
        page1.setCurrent(page);
        page1.setRecords(PageUtil.yydzPage(page,limit,resultList));
        page1.setSize(limit);
        page1.setTotal(resultList.size());
        page1.setPages(getPages(page1.getSize(), page1.getTotal()));
        LayuiPageInfo pageBySpec = LayuiPageFactory.createPageInfo(page1);
        pageBySpec.setData(PageUtil.yydzPage(page,limit,resultList));
        return pageBySpec;
    }

    private long getPages(long size, long total) {
        if (size == 0L) {
            return 0L;
        } else {
            long pages = total / size;
            if (total % size != 0L) {
                ++pages;
            }

            return pages;
        }
    }

    /**
     * 同步店名
     * @return
     */
    @Override
    public ResponseData synList() {
        //获取bty_brand表全部店名
        List<BtyBrand> brandList = brandMapper.getList();
        List<String> bhList = new ArrayList<>();//编号集合
        for (BtyBrand btyBrand : brandList) {
            String bh = btyBrand.getBh();
            bhList.add(bh);
        }
        //获取店名对应角色
        List<Map> mapList = shopMapper.getList(bhList);
        
        Map<String, BtyBrand> brandMap = brandList.stream().collect(Collectors.toMap(BtyBrand::getBh, Function.identity()));
        List<BtyMdYydz> list = mapList.stream().map(h -> {
            BtyBrand brand = brandMap.get(h.get("code"));

            BtyMdYydz btyMdYydz = new BtyMdYydz();
            btyMdYydz.setDm(brand.getDm());//店名
            btyMdYydz.setYaoma(brand.getYaoma());//妖码
            btyMdYydz.setCwm(brand.getCwm());//财务码
            btyMdYydz.setYyjl(ToolUtil.isNotEmpty(h.get("yyName")) ? h.get("yyName").toString() : null);//营运经理姓名
            btyMdYydz.setDd(ToolUtil.isNotEmpty(h.get("ddName")) ? h.get("ddName").toString() : null);//督导姓名
            btyMdYydz.setDdz(ToolUtil.isNotEmpty(h.get("ddzName")) ? h.get("ddzName").toString() : null);//大店长姓名
            btyMdYydz.setDz(ToolUtil.isNotEmpty(h.get("dzName")) ? h.get("dzName").toString() : null);//店长姓名
            btyMdYydz.setDzTel(ToolUtil.isNotEmpty(h.get("dzTel")) ? h.get("dzTel").toString() : null);//店长电话
            btyMdYydz.setYyTel(ToolUtil.isNotEmpty(h.get("yyTel")) ? h.get("yyTel").toString() : null);//营运经理电话
            btyMdYydz.setDdTel(ToolUtil.isNotEmpty(h.get("ddTel")) ? h.get("ddTel").toString() : null);//督导电话
            btyMdYydz.setDdzTel(ToolUtil.isNotEmpty(h.get("ddzTel")) ? h.get("ddzTel").toString() : null);//大店长电话
            btyMdYydz.setCode(brand.getBh());//门店编号
            return btyMdYydz;

        }).collect(Collectors.toList());

        for (BtyMdYydz mdYydz: list ) {
            //查询数据库是否有该数据
            int con = baseMapper.getCon(mdYydz.getCode());
            if (con != 0){
                //修改
                baseMapper.updateByCode(mdYydz);
            }else {
                //新增
                baseMapper.insert(mdYydz);
            }
        }
        //获取城市
        List<Map> city = baseMapper.getCity();
        if (ToolUtil.isNotEmpty(city)){
            //每150条保存一次
            for(int i = 0; i < city.size();){
                int i2 = (i + 150);
                i2 = i2 > city.size() ? city.size() : i2;
                List<Map> sub = city.subList(i, i2);
                //修改数据库城市
                baseMapper.updateCity(sub);
                i = i2;
            }
        }

        return ResponseData.success();
    }

    /**
     * 获取城市列表
     * @return
     */
    @Override
    public ResponseData cityList() {
        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();
        List<Map> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = this.baseMapper.cityList(null);
        }else if (roleNames.contains("应收会计")){
            //获取应收会计所对应店名编号
            List<String> bhList = this.baseMapper.bhList(name);
            list = this.baseMapper.cityList(bhList);
        }

        return ResponseData.success(list);
    }

    /**
     * 导出
     * @param date
     * @return
     */
    @Override
    public void exportList(String date, HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String number = sdf.format(new Date());

        //当前登陆者姓名
        String name = LoginContextHolder.getContext().getUser().getName();
        //当前登陆者角色
        List<String> roleNames = LoginContextHolder.getContext().getUser().getRoleNames();

        //获取要导出数据
//        List<Map> list = this.baseMapper.exportList(date);
        List<Map> list = new ArrayList<>();

        if (roleNames.contains("超级管理员") || roleNames.contains("财务主管")){
            list = this.baseMapper.exportList(date, null);
        }else if (roleNames.contains("应收会计")){
            //获取应收会计所对应店名编号
            List<String> bhList = this.baseMapper.bhList(name);
            list = this.baseMapper.exportList(date, bhList);
        }

        String fileName = number + "营业额对账表";
        String path = "D:\\" + "xls\\";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs(); //创建目录
        }
        String url = path + fileName + ".xls";
        try {
            //map数据
            List<String[]> dataset = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                String[] arr = new String[17];
                arr[0] = i + 1 + "";
                arr[1] = list.get(i).get("dm") == null ? "" : list.get(i).get("dm").toString();
                arr[2] = list.get(i).get("yaoma") == null ? "" : list.get(i).get("yaoma").toString();
                arr[3] = list.get(i).get("cwm") == null ? "" : list.get(i).get("cwm").toString();
                arr[4] = list.get(i).get("city") == null ? "" : list.get(i).get("city").toString();
                arr[5] = list.get(i).get("yyjl") == null ? "" : list.get(i).get("yyjl").toString();
                arr[6] = list.get(i).get("dd") == null ? "" : list.get(i).get("dd").toString();
                arr[7] = list.get(i).get("ddz") == null ? "" : list.get(i).get("ddz").toString();
                arr[8] = list.get(i).get("dz") == null ? "" : list.get(i).get("dz").toString();
                arr[9] = list.get(i).get("dz_tel") == null ? "" : list.get(i).get("dz_tel").toString();
                arr[10] = list.get(i).get("report_type") == null ? "" : list.get(i).get("report_type").toString();
                arr[11] = list.get(i).get("dz_apply") == null ? "" : list.get(i).get("dz_apply").toString();
                arr[12] = list.get(i).get("cw_approve") == null ? "" : list.get(i).get("cw_approve").toString();
                arr[13] = list.get(i).get("dz_replay") == null ? "" : list.get(i).get("dz_replay").toString();
                arr[14] = list.get(i).get("final_method") == null ? "" : list.get(i).get("final_method").toString();

                String dz_msg = list.get(i).get("dz_msg") == null ? "" : list.get(i).get("dz_msg").toString();
                String dd_msg = list.get(i).get("dd_msg") == null ? "" : list.get(i).get("dd_msg").toString();
                arr[15] = dz_msg + "," + dd_msg;
                dataset.add(arr);
            }
            //外卖导出表头
            String[] handers1 = {"序号", "店名","妖码","财务码", "城市区域", "营运经理", "督导", "大店长", "店长", "店长电话",
                    "店长报备状态", "店长报备问题", "财务审核情况", "店长回复审核情况", "最终解决方式", "状态"};
            //对象
            ExcelExp fymx = new ExcelExp("营业额对账表", handers1, dataset);
            List<ExcelExp> mysheet = new ArrayList<>();
            mysheet.add(fymx);
            //生成sheet
            ExcelUtil.exportManySheetExcel(url, mysheet);
            //下载sheet
            ExcelUtil.getExcel(url, fileName, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Serializable getKey(BtyMdYydzParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyMdYydz getOldEntity(BtyMdYydzParam param) {
        return this.getById(getKey(param));
    }

    private BtyMdYydz getEntity(BtyMdYydzParam param) {
        BtyMdYydz entity = new BtyMdYydz();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
